package com.zhaoyd.uaademo.api.gitee;

import com.zhaoyd.uaademo.api.gitee.entity.GiteeToken;
import com.zhaoyd.uaademo.api.gitee.entity.GiteeUserInfo;
import com.zhaoyd.uaademo.core.BaseLogger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhaoyd
 * @date 2020-11-09 20:19
 */
@Component
public class GiteeApi extends BaseLogger {
    @Value("${gitee.client.id}")
    private String clientId;
    @Value("${gitee.client.secret}")
    private String clientSecret;


    public GiteeToken getToken(String code){
        String url = "https://gitee.com/oauth/token";
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String,Object> paramMap = new LinkedMultiValueMap<String,Object>();
        //固定授权码模式
        paramMap.add("grant_type","authorization_code");
        paramMap.add("client_id","1d8b753d6f17789dfcc12192802d53a4f0c3217bc29099ba7d0829fd7fb4c659");
        paramMap.add("client_secret","138a2a34d5d1476aa264aec648b1a3a32ca0ab790f5430ad65f15397f8bbe244");
        //回调地址待确认作用
        paramMap.add("redirect_uri","http://122.51.119.99:8091/auth/callback/gitee");
        paramMap.add("code",code);

        HttpHeaders headers = new HttpHeaders();
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap,headers);
        ResponseEntity<GiteeToken> responseEntity = restTemplate.postForEntity(url,httpEntity, GiteeToken.class);
        return responseEntity.getBody();
    }

//    public static void main(String[] args) {
//        //new GiteeApi().getToken("e9337980d7ca920fbbab954932e43af6d00a7aba8371d2a3d2defec2dc9c3644");
//        new GiteeApi().getUserInfo("6a4a6857b595019a23eedb92558e0eef");
//    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    public GiteeUserInfo getUserInfo(String token){
        String url = "https://gitee.com/api/v5/user?access_token="+token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity httpEntity = new HttpEntity<>(headers);
        ResponseEntity<GiteeUserInfo> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, GiteeUserInfo.class);
        return response.getBody();
    }
}
